const http = require('http');
const queryString = require('querystring');

const server = http.createServer();

server.on('request', (req, res) => {

    res.setHeader('Content-Type', 'text/html;charset=utf-8');

    if (req.url == '/user') {
        let cookies = null;
        try {
            cookies = queryString.parse(req.headers.cookie, '; ');
        } catch (e) {
            res.statusCode = 401;
            res.end('没有权限');
        }
        if (!cookies.user) {
            res.statusCode = 401;
            res.end('没有权限');
        } else {
            res.end('大海和小蕊');
        }
    }

    if (req.method.toLowerCase() == 'post' && req.url == '/login') {
        let user = {
            id: 1,
            username: 'zMouse'
        };
        // 设置cookie
        res.setHeader('Set-Cookie', `user=${JSON.stringify(user)}`);
        // 设置多个cookie
        // res.setHeader('Set-Cookie', ['a=1', 'b=2']);
        res.end('授权成功');
    }
});

server.listen(8888);
